#/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
from lib.log import logger
from lib.gitclient import GitClient




def main():
    parser = argparse.ArgumentParser(description="code-manager script")
    parser.add_argument("--url", type=str, default='https://code.cestc.cn', help="gitlab地址")
    parser.add_argument("--access_token", type=str, default='', help="gitlab access_token")
    parser.add_argument("--base_branch", type=str, default='master', help="原始分支")
    parser.add_argument("--target_branch", type=str, default='zhouyi', help="目标分支")
    parser.add_argument("--projects", type=str, default='console-plugin-ies,multi-cluster-sdk,ies-store,streampipes-operator,streampipes,streampipes-gateway,apiserver-network-proxy,karmada,multi-cluster-operator', help="目标分支")
    args = parser.parse_args()
    logger.info(f"url={args.url}")
    logger.info(f"access_token={args.access_token}")
    logger.info(f"base_branch={args.base_branch}")
    logger.info(f"target_branch={args.target_branch}")
    logger.info(f"projects={args.projects}")

    for project_name in args.projects.strip().split(','):
        project_name = project_name.strip()
        if project_name == '':
            continue
        logger.debug(f"project_name={project_name}")
        gitClient = GitClient(args.url, args.access_token)
        project_id = gitClient.GetProjectID(project_name)
        logger.info(f"------------------id:{project_id} --- {project_name}----------------")

        exist = gitClient.existBranch(project_id, args.target_branch)
        if exist:
            same = gitClient.isSameBranch(project_id, args.target_branch, args.base_branch)
            if not same:
                logger.info(f"*******************应该删除 {args.target_branch}")
                gitClient.DeleteBranch(project_id, args.target_branch)
                gitClient.createBranch(project_id, args.base_branch, args.target_branch)
        else:
            gitClient.createBranch(project_id, args.base_branch, args.target_branch)

if __name__ == "__main__":
    main()